package com.atguigu.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class FastJsonDemo1 {
    /*
    * JSON: 最根本的类. 抽象的JSON格式的数据
    *       jsonstr转java对象: JSON.parse
    *       java对象转jsonstr: JSON.toJSONString
    *
    * JSONObject: 代表{}格式的java对象,类似Map
    *           获取某个属性名的值: get(key)
    *           向JSONObject放一个K-V对: put(key,value)
    *
    * JSONArray: 代表[]格式的java对象,类似List
    *           获取某个元素: get(index)
    *           向JSONArray放一个元素: add(ele)
    * */
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        Employee emp = new Employee(1,"jack","male","jack@qq.com");
        Employee emp1 = new Employee(2,"wzx","male","wzx@qq.com");
        employees.add(emp);
        employees.add(emp1);
        //java对象转jsonstr
        String jsonstr = JSON.toJSONString(emp);
        String jsonarraystr = JSON.toJSONString(employees);
        //jsonstr转java对象并进行查询和插入操作
        Employee employee = JSON.parseObject(jsonstr, Employee.class);

        JSONObject jsonObject = JSON.parseObject(jsonstr);
        System.out.println(jsonObject.getString("gender"));
        jsonObject.put("address","shenzhen");
        System.out.println(jsonObject);

        List<Employee> employees1 = JSON.parseArray(jsonarraystr, Employee.class);
        JSONArray objects = JSON.parseArray(jsonarraystr);
        Employee object = objects.getObject(0, Employee.class);
        objects.add(0,object);
        System.out.println(objects);
    }
}
